package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.constant.AuthConstant;
import cn.com.dcsgo.strategy.LoginStrategy;
import cn.com.dcsgo.strategy.LoginStrategyFactory;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * UserDetailsService实现类
 *
 * @author Dcsgo
 * @since 2025/9/17 10:51
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private LoginStrategyFactory loginStrategyFactory;

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return UserDetails 用户信息
     * @throws UsernameNotFoundException 用户名不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过请求头中的登录类型区分是后台管理员登录还是小程序用户登录
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new InternalAuthenticationServiceException("无法获取请求上下文，请确保在请求环境中调用");
        }
        HttpServletRequest request = attributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        log.debug("loginType:{}", loginType);
        if (!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("登录类型不能为空");
        }
        LoginStrategy loginStrategy = loginStrategyFactory.getLoginStrategy(loginType);
        if (loginStrategy == null) {
            throw new InternalAuthenticationServiceException("登录类型不存在");
        }
        return loginStrategy.realLogin(username);
    }
}
